from nonebot import on_startswith
from nonebot.adapters import Event
from nonebot.adapters.onebot.v11 import MessageSegment
from .compile import Compile

import requests

import re

command = on_startswith(("/latex -u", "/latex --url"))

@command.handle()
async def handler(event: Event):
    message = event.get_message().extract_plain_text().replace("/latex -u", "", 1).replace("/latex --url", "", 1)

    message = message.replace('https://pastebin.com/', 'https://pastebin.com/raw/')

    if re.search(r"paste\.ubuntu\.com", message):
        message = message + '/plain'
        headers = {
            # 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
            'Host': 'paste.ubuntu.com',
            # 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8'
        }

        cookies = {
            'sessionid': 'yntnaxqjax6zrqu7ve2vetgxqdb8trh3'  # 使用你的cookie值
        }
    else:
        headers = {}
        cookies = {}

    try:

        # 发送GET请求
        response = requests.get(message, headers=headers, cookies=cookies)

        response.encoding = 'utf-8'
        response.raise_for_status()  # 检查是否请求成功
    except requests.exceptions.RequestException as e:
        print(f"请求出错: {e}")

    response.raise_for_status()
    result = Compile(response.text.replace('\r\n', '\n').replace('\r', '\n')).run()
    for item in result:
        await command.send(MessageSegment.image(item))
    await command.finish()
   